//
//  FPSView.m
//  RBIOSBase
//
//  Created by ren on 08/12/2017.
//  Copyright © 2017 bryan. All rights reserved.
//

#import "FPSView.h"

@interface FPSView ()

@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic, assign) NSInteger scheduleTimes;
@property (nonatomic, assign) CFTimeInterval timestamp;
@property (nonatomic, strong) UILabel *fpsLabel;

@end

@implementation FPSView

- (instancetype)initWithFrame:(CGRect)frame
{
	if (self = [super initWithFrame:frame]) {
		[self addFpsLabel];
		_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(linkTicks:)];
		[_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
	}
	return self;
}

- (void)linkTicks:(CADisplayLink *)link
{
	_scheduleTimes ++;
	
	if (_timestamp == 0) {
		_timestamp = link.timestamp;
	}
	CFTimeInterval timePassed = link.timestamp - _timestamp;
	
	if (timePassed >= 1.f) {
		//fps
		CGFloat fps = _scheduleTimes/timePassed;
		printf("fps:%.1f, timePassed:%f\n", fps, timePassed);
		[_fpsLabel setText:[@"FPS:" stringByAppendingFormat:@"%.1f", fps]];
		
		//reset
		_timestamp = link.timestamp;
		_scheduleTimes = 0;
	}
}

- (void)addFpsLabel
{
	_fpsLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];
	[_fpsLabel setTextColor:[UIColor whiteColor]];
	[self addSubview:_fpsLabel];
}

@end
